/*
 * This file is part of quickReminder, a software for gamers
 *
 * Copyright (C) 2006-2008 Lucas Romero
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Runtime.InteropServices;
//using GA_ScreenScraper;
//using KeyboardBlinker;
using System.Collections;
using System.Collections.Specialized;
//using MrSmarty.CodeProject;
using LucasCode;
using LucasCode.Tools;
using LucasCode.UpdateChecker;
using LucasCode.UpdateForm;
using ESLReminder;
using ManagedWinapi;
using ManagedWinapi.Windows;
using ManagedWinapi.Accessibility;
using LucasCode.Win32;
using Microsoft.Win32;

namespace quickReminder
{
    public sealed class SysTrayIcon : NativeWindow
	{
        private class NativeMethods
        {
            [DllImport("user32.dll")]
            public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
            [DllImport("user32.dll")]
            public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref COPYDATASTRUCT data);

            public const short WM_COPYDATA = 74;

            public struct COPYDATASTRUCT
            {
                public IntPtr dwData;
                public IntPtr cbData;
                public IntPtr lpData;
            }
        }
		ArrayList FileSystemWatchers = new ArrayList();
        DateTime LastWriteDate = DateTime.Now;
		private System.Windows.Forms.NotifyIcon trayIcon;
        private System.Windows.Forms.ContextMenuStrip sysTrayMenu2;
        private string GameName = string.Empty;
        private string ModName = string.Empty;
        //public static string AppDir = Path.GetDirectoryName(Application.ExecutablePath);

		//private System.Resources.ResourceManager lang;
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SysTrayIcon));
        public ESLReminder.ESLReminder reminder;
        private string m_MatchLink;
        AutoUpdateChecker updatechecker;
        Hotkey HotkeyIgnore;
        bool GameRunning = false;
        ConsoleEventItemCollection eventcollection = new ConsoleEventItemCollection();

        private StringCollection GatheredFiles = new StringCollection();
		private bool debug
		{
			get
			{
				return true;
			}
		}
        
		#region Initialize icon and menu
		public SysTrayIcon()
		{
            CreateParams cp = new CreateParams();
            //cp.ClassName = Class;
            cp.Caption = "quickReminder_hwnd"; //The window title is the same as the Id
            CreateHandle(cp);
            //Application.CurrentCulture = new System.Globalization.CultureInfo("de", false);
            if (Properties.Settings.Default.NewVersionInstalled)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.NewVersionInstalled = false;
            }
            if (Properties.Settings.Default.DemoWriteLimit < 5)
                Properties.Settings.Default.DemoWriteLimit = 5;
            Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
            Thread.CurrentThread.IsBackground = true;
            //System.Diagnostics.Process.GetCurrentProcess().BasePriority = 1;
            System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
            if (Properties.Settings.Default.SetAffinityquickReminder && Properties.Settings.Default.AffinityquickReminder < System.Environment.ProcessorCount)
            {
                System.Diagnostics.Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1 << Properties.Settings.Default.AffinityquickReminder);
            }
			//lang = new System.Resources.ResourceManager("quickReminder.lang",GetType().Assembly);
			trayIcon = new NotifyIcon();
			//sysTrayMenu = new ContextMenu(InitializeMenu());
            sysTrayMenu2 = new ContextMenuStrip();
            sysTrayMenu2.Opening += new System.ComponentModel.CancelEventHandler(sysTrayMenu2_Opening);
            sysTrayMenu2.ShowCheckMargin = false;
            sysTrayMenu2.ShowItemToolTips = false;
            sysTrayMenu2.Items.AddRange(InitializeMenu2());
			trayIcon.DoubleClick += TrayIconDoubleClick;
			trayIcon.Icon = (Icon)resources.GetObject("enabled_small");
			//trayIcon.ContextMenu = sysTrayMenu;
            trayIcon.ContextMenuStrip = sysTrayMenu2;
			trayIcon.Text = Application.ProductName + " " + Application.ProductVersion;
            trayIcon.BalloonTipClicked += new EventHandler(trayIcon_BalloonTipClicked);
            reminder = new ESLReminder.ESLReminder();
            reminder.GameStarted += new ESLReminder.ESLReminder.GameStartedEventHandler(reminder_GameStarted);
            reminder.GameExited += new ESLReminder.ESLReminder.GameExitedEventHandler(reminder_GameExited);
            reminder.FilesCollected += new ESLReminder.ESLReminder.FilesCollectedEventHandler(reminder_FilesCollected);
            reminder.StatusTextChanged += new ESLReminder.ESLReminder.StatusTextChangedEventHandler(reminder_StatusTextChanged);
            reminder.OnException += new ESLReminder.ESLReminder.OnExceptionEventHandler(reminder_OnException);

            SetUpReminder();
            if (Properties.Settings.Default.HotkeyActive)
            {
                try
                {
                    HotkeyIgnore = new Hotkey();
                    HotkeyIgnore.KeyCode = (Keys)Properties.Settings.Default.HotkeyNum;
                    HotkeyIgnore.Ctrl = Properties.Settings.Default.HotkeyCtrl;
                    HotkeyIgnore.Alt = Properties.Settings.Default.HotkeyAlt;
                    HotkeyIgnore.Shift = Properties.Settings.Default.HotkeyShift;
                    HotkeyIgnore.Enabled = true;
                    HotkeyIgnore.HotkeyPressed += new EventHandler(HotkeyIgnore_HotkeyPressed);
                }
                catch(Exception e)
                {
                    MessageBox.Show("Error while setting up Hotkey!", e.Message);
                }
            }
            if (Properties.Settings.Default.PseudoUniqueID == string.Empty)
            {
                char[] symbols = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
                Random r = new Random();
                while (Properties.Settings.Default.PseudoUniqueID.Length < 20)
                    Properties.Settings.Default.PseudoUniqueID += symbols[r.Next(62)];
            }
            Properties.Settings.Default.Save();
            if(Properties.Settings.Default.AutoCheckForUpdates && Properties.Settings.Default.LastUpdateCheck.Date != DateTime.Now.Date)
            {
                if(updatechecker == null)
                    updatechecker = new AutoUpdateChecker();
                updatechecker.UpdateCheckComplete += new AutoUpdateChecker.UpdateCheckCompleteEventHandler(updatechecker_UpdateCheckComplete);
                updatechecker.hasUpdateAsync(Properties.Settings.Default.UpdateURL, new Version(Application.ProductVersion), new UsageInfo(Properties.Settings.Default.PseudoUniqueID, Application.ProductVersion));
            }
            //foreach (System.Globalization.CultureInfo i in System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.FrameworkCultures))
                //MessageBox.Show(i.DisplayName);
            //Application.CurrentCulture = typeof(lang).
            //Application.CurrentCulture = new System.Globalization.CultureInfo(System.Globalization.CultureInfo.GetCultureInfo("German").LCID, false);
            //int len = Environment.GetCommandLineArgs().Length;
            string[] bla = Environment.GetCommandLineArgs();
            bla[0] = string.Empty;
            //Environment.GetCommandLineArgs().CopyTo(bla, len-1)
            OpenArchiveFiles(bla);
            if (Properties.Settings.Default.CheckQmaAssociation && !isExtensionInstalled())
                if (MessageBox.Show("quickReminder-archives (*.qma-files) are currently not associated with this program\r\nDo you want me to associate them now?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    RegisterExtension();
		}

        bool isExtensionInstalled()
        {
            RegistryKey key;
            key = Registry.ClassesRoot.OpenSubKey(".qma");
            if (key == null)
                return false;
            string assoc = (string)key.GetValue("");
            key = Registry.ClassesRoot.OpenSubKey(assoc);
            if (key == null)
                return false;
            key = key.OpenSubKey("shell");
            if (key == null)
                return false;
            key = key.OpenSubKey("open");
            if (key == null)
                return false;
            key = key.OpenSubKey("command");
            if (key == null)
                return false;
            if (string.Compare((string)key.GetValue(""), "\"" + Application.ExecutablePath + "\" \"%1\"", true) != 0)
                return false;
            return true;
        }

        void RegisterExtension()
        {
            try
            {
                string keyName;
                string keyValue;
                //This creates a Root entry called "MyApp".
                keyName = "qR";
                keyValue = "quickReminder";

                RegistryKey key;
                key = Registry.ClassesRoot.CreateSubKey(keyName);
                key.SetValue("", keyValue);
                key = key.CreateSubKey("shell");
                key = key.CreateSubKey("open");
                key = key.CreateSubKey("command");
                key.SetValue("", "\"" + Application.ExecutablePath + "\" \"%1\"");

                keyName = ".qma";
                keyValue = "qR";
                key = Registry.ClassesRoot.CreateSubKey(keyName);
                key.SetValue("", keyValue);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void sysTrayMenu2_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //if (GatheredFiles.Count > 0)
                sysTrayMenu2.Items["ManualUpload"].Visible = true;
            //else
                //sysTrayMenu2.Items["ManualUpload"].Visible = false;

#if DEBUG
sysTrayMenu2.Items["ManualUpload"].Visible = true;
#endif

            
        }

        void updatechecker_UpdateCheckComplete(AutoUpdateChecker sender, UpdateCheckEventArgs e)
        {
            if(!e.Failed)
                Properties.Settings.Default.LastUpdateCheck = DateTime.Now;
            if (e.hasUpdate)
                if (MessageBox.Show(quickReminder.lang.UpdateAvailable, "quickReminder - " + quickReminder.lang.UpdateAvailableTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    using (FormUpdate fupd = new FormUpdate(sender))
                        fupd.ShowDialog();
                }
        }

        void HotkeyIgnore_HotkeyPressed(object sender, EventArgs e)
        {
            //MessageBox.Show("kjdhklasjdfkh");
            if(GameRunning)
                reminder.IgnoreWarnings();
        }

        void reminder_OnException(ESLReminder.ESLReminder sender, Exception ex)
        {
            //MessageBox.Show("An Error occured!")
        }
        void SetUpReminder()
        {
            
            reminder.LoginCookie = Properties.Settings.Default.Cookie;
            reminder.WarnAlways = Properties.Settings.Default.AlwaysWarn;
            reminder.WarnOnNoDemo = Properties.Settings.Default.WarnOnNoDemo;
            reminder.OverwriteProtectionEnabled = Properties.Settings.Default.OverWriteProtectionEnabled;
            reminder.DebugEnabled = Properties.Settings.Default.EnableDebug;
            reminder.OffsetBefore = new TimeSpan(0, Properties.Settings.Default.MaxTimeDifferenceBefore, 0);
            reminder.OffsetAfter = new TimeSpan(0, Properties.Settings.Default.MaxTimeDifferenceAfter, 0);

            reminder.SetPrioGame= Properties.Settings.Default.SetPriorityGame;

            reminder.SetAffinityAequitas = Properties.Settings.Default.SetAffinityAequitas;
            reminder.SetAffinityGame = Properties.Settings.Default.SetAffinityGame;
            reminder.ProcessAffinityAequitas = Properties.Settings.Default.AffinityAequitas;
            reminder.ProcessAffinityGame = Properties.Settings.Default.AffinityGame;

            reminder.DemoTimerInterval = Properties.Settings.Default.DemoWriteLimit *1000;
            reminder.WarnOnTeamchange = Properties.Settings.Default.WarnOnTeamchange;
            reminder.WarnOnNoDemo = Properties.Settings.Default.WarnOnNoDemo;
            reminder.WarnOnNoStatus = Properties.Settings.Default.WarnOnNoStatus;
            reminder.DisableDebugMonitor = !Properties.Settings.Default.EnableConsoleParsing;
            reminder.ParseConsoleAlways = !Properties.Settings.Default.ParseConsoleOnlyOnLeagueMatch;
            reminder.FreeDiskspaceWarnThreshold = Properties.Settings.Default.FreeDiskspaceWarnThreshold;
            MatchFile.UploadSettings.JpegCompression = Properties.Settings.Default.JPGCompressionQuality;

            reminder.MatchFilter.Clear();
            foreach (string s in Properties.Settings.Default.MatchFilter)
                reminder.MatchFilter.Add(s);
            
        }

        void OpenArchiveFiles(string[] files)
        {
            foreach (string s in files)
            {
                if (!string.IsNullOrEmpty(s))
                {
                    //FormViewArchive f = new FormViewArchive();
                    //f.ShowArchiveContent(s);
                    FormUpload f = new FormUpload(s);
                    f.Show();
                }
            }
        }

        void reminder_StatusTextChanged(ESLReminder.ESLReminder sender, string text)
        {
            String status = text + Environment.NewLine + Application.ProductName + " " + Application.ProductVersion;
            if (status.Length < 64)
                trayIcon.Text = status;
            else if (text.Length < 64)
                trayIcon.Text = text;
            else
                trayIcon.Text = text.Substring(0, 63);
        }

        void reminder_FilesCollected(ESLReminder.ESLReminder sender, System.Collections.Specialized.StringCollection FileList, string MatchURL,ConsoleEventItemCollection events)
        {
            m_MatchLink = MatchURL;
            eventcollection.Clear();
            foreach(ConsoleEventItem ev in events)
            {
                eventcollection.Add(new ConsoleEventItem(ev.EventTime, ev.EventType, ev.EventText));
            }
            GatheredFiles.Clear();
            foreach (string file in FileList)
                GatheredFiles.Add(file);
            if (GatheredFiles.Count > 0)
                trayIcon.ShowBalloonTip(Properties.Settings.Default.UploadHelperTimeout, lang.FilesCollectedHintTitle, lang.FilesCollectedHintText, ToolTipIcon.Info);
            //System.Text.StringBuilder s = new System.Text.StringBuilder();
            
            //MessageBox.Show("Files created during the match: " + Environment.NewLine + s.ToString());
        }

        void trayIcon_BalloonTipClicked(object sender, EventArgs e)
        {
            //MessageBox.Show("Files created during the match: " + Environment.NewLine + s.ToString());
            using (FormUpload up = new FormUpload(m_MatchLink,Properties.Settings.Default.Cookie, GatheredFiles,eventcollection, reminder.GameName, reminder.Mod))
                up.ShowDialog();
        }

        void reminder_GameExited(ESLReminder.ESLReminder sender)
        {
            GameRunning = false;
            try
            {
                trayIcon.Icon = (Icon)resources.GetObject("enabled_small");
            }
            catch { }
            
            if (HotkeyIgnore != null)
                HotkeyIgnore.Enabled = false;
        }

        //public delegate void GameStartedInvoker(ESLReminder.ESLReminder sender, bool LeagueMatch);
        void GameStarted(object data)
        {
            Trace.WriteLine("SysTrayIcon: Entering GameStarted()");
            ESLReminder.ESLReminder sender = data as ESLReminder.ESLReminder;
            if (HotkeyIgnore != null)
                try { HotkeyIgnore.Enabled = true; }
                catch(Exception ex)
                {
                    //just catch 
                    Trace.WriteLine("Error registering hotkey: " + ex.Message);
                }
            trayIcon.Icon = (Icon)resources.GetObject("monitoring");
            Process[] procs = Process.GetProcesses();
            foreach (String s in Properties.Settings.Default.ProcessOptimizerList)
            {
                string[] procinfo = s.Split(new string[] { Properties.Settings.Default.ProcessOptimizerListSplitter }, StringSplitOptions.None);
                if (procinfo.Length < 3)
                    /* wrong format */
                    continue;
                foreach (Process p in procs)
                {
                    /* strip *.exe from name */
                    if (procinfo[0].ToLower().EndsWith(".exe"))
                        procinfo[0] = procinfo[0].Substring(0, procinfo[0].Length - 4);
                    if (String.Compare(p.ProcessName, procinfo[0], true) == 0)
                    {
                        if (procinfo.Length >= 4 && Convert.ToBoolean(procinfo[3]))
                        {
                            //new format with "kill?" argument
                            p.Kill();
                        }
                        else
                        {
                            if (procinfo[1] != "All CPUs")
                            {
                                try
                                {
                                    p.ProcessorAffinity = new IntPtr(1 << Int32.Parse(procinfo[1].Substring(4)));
                                }
                                catch (Exception ex)
                                {
                                    Trace.WriteLine("Couldn't change processor affinity! Error: " + ex.Message);
                                }
                            }

                            try
                            {
                                p.PriorityClass = (ProcessPriorityClass)Enum.Parse(typeof(ProcessPriorityClass), procinfo[2]);
                            }
                            catch (ArgumentException)
                            {
                                p.PriorityClass = ProcessPriorityClass.Normal;
                            }
                        }
                    }
                }
            }
            Trace.WriteLine("SysTrayIcon: Leaving GameStarted()");
        }

        void reminder_GameStarted(ESLReminder.ESLReminder sender, bool LeagueMatch)
        {
            Trace.WriteLine("SysTrayIcon: Entering reminder_GameStarted()");
            GameRunning = true;
            ModName = sender.Mod;
            GameName = sender.GameName;
            ThreadPool.QueueUserWorkItem(new WaitCallback(GameStarted), sender);
            Trace.WriteLine("SysTrayIcon: Leaving reminder_GameStarted()");
        }
	    ~SysTrayIcon()
        {
	    }
        private ToolStripItem[] InitializeMenu2()
        {
            ToolStripItem[] menu = new ToolStripItem[] {
                new ToolStripMenuItem(lang.ManualUpload, lang.up16, menuUploadManualClick, "ManualUpload"),
				//new MenuItem(gs("DontWarn"), menuStopMonitoringClick),
                new ToolStripMenuItem(lang.AequitasChecker, lang.apply16, AequitasCheckerClick),
                //new ToolStripMenuItem("Instant Challenger", lang.test16, menuChallenger),
                new ToolStripSeparator(),
                new ToolStripMenuItem(lang.Settings, lang.screwdriver_16, menuSettingsClick),
/*#if DEBUG
                new ToolStripMenuItem("Test Upload",null,menuTest2Click),
                //new MenuItem("TestMatchURL",menuTest3Click),
#endif*/
                new ToolStripMenuItem(lang.Tools, lang.tools16, new ToolStripItem[] {
#if DEBUG
                    new ToolStripMenuItem("Archive browser", null, menuArchiveBrowser),
                    new ToolStripMenuItem("Match Monitor", null, menuMatchMonitor),
#endif
                    
                    new ToolStripMenuItem(lang.ELOCalculator, lang.kcalc16, menuELOClick), 
                    new ToolStripMenuItem(lang.CreateAequitasLogin, lang.user16, menuCreateSessionClick, "CreateLogin"),
                    new ToolStripMenuItem("Aequitas Benchmark", lang.aequitas16, menuAequitasBenchmarkClick, "AequitasBenchmark"),
                    new ToolStripSeparator(),
                    new ToolStripMenuItem(lang.About, lang.help16, menuAboutClick),
                    new ToolStripMenuItem(lang.ReportBug, lang.bug16, menuReportClick),
                }),

                new ToolStripSeparator(),
				new ToolStripMenuItem(lang.Exit, lang.exit16, menuExitClick)
			};
            
            return menu;
        }
		#endregion

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == NativeMethods.WM_COPYDATA)
            {
                
                //convert the message LParam to the WM_COPYDATA structure
                NativeMethods.COPYDATASTRUCT data = (NativeMethods.COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(NativeMethods.COPYDATASTRUCT));
                //Marshal.PtrToStringAuto
                System.Text.UnicodeEncoding u = new System.Text.UnicodeEncoding();
                byte[] b = new byte[data.cbData.ToInt32()];
                Marshal.Copy(data.lpData, b, 0, data.cbData.ToInt32());
                string bla = u.GetString(b);
                OpenArchiveFiles(bla.Split(new string[] { "_@@_" }, StringSplitOptions.None));
                //MessageBox.Show(bla);
            }
            else
                base.WndProc(ref m);
        }
		#region Main - Program entry point
		/// <summary>Program entry point.</summary>
		/// <param name="args">Command Line Arguments</param>
		[STAThread]
		public static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
#endif
			
			bool isFirstInstance;
			// Please use a unique name for the mutex to prevent conflicts with other programs
			using (Mutex mtx = new Mutex(true, "quickReminder", out isFirstInstance)) {
				if (isFirstInstance) {
                    if (Properties.Settings.Default.LanguageString != String.Empty)
                    {
                        lang.Culture = new System.Globalization.CultureInfo(Properties.Settings.Default.LanguageString);
                        Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Properties.Settings.Default.LanguageString);
                    }
                    //MessageBox.Show(Application.StartupPath);
                    Directory.SetCurrentDirectory(Application.StartupPath);
					SysTrayIcon sysTrayIcon = new SysTrayIcon();
					sysTrayIcon.trayIcon.Visible = true;
                    //System.Globalization.CultureInfo.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo("de");
                    //try { Application.CurrentCulture = new System.Globalization.CultureInfo("de-DE", false); }
                    //catch (Exception ex) { MessageBox.Show(ex.Message, ex.StackTrace); }
					Application.Run();
                    sysTrayIcon.reminder_StatusTextChanged(null, "Stopping WarnModules");
                    sysTrayIcon.reminder.WarnModules.Stop();
                    DbMon.NET.DebugMonitor.Stop();
					quickReminder.Properties.Settings.Default.Save();
					sysTrayIcon.trayIcon.Dispose();
				} else {
					// The application is already running
                    NativeMethods.COPYDATASTRUCT data = new NativeMethods.COPYDATASTRUCT();
                    System.Text.UnicodeEncoding u = new System.Text.UnicodeEncoding();

                    string bla = string.Join("_@@_", args);
                    IntPtr strMem = Marshal.AllocCoTaskMem(u.GetByteCount(bla));
                    //FIXME: switch to easier version of allocating string resource in co-task mem:
                    //IntPtr strMem = Marshal.StringToCoTaskMemAuto(bla);
                    data.cbData = new IntPtr(u.GetByteCount(bla));
                    data.lpData = strMem;
                    data.dwData = IntPtr.Zero;

                    Marshal.Copy(u.GetBytes(bla), 0, strMem, u.GetByteCount(bla));
                    IntPtr orgwin = NativeMethods.FindWindow(null, "quickReminder_hwnd");
                    NativeMethods.SendMessage(orgwin, NativeMethods.WM_COPYDATA, IntPtr.Zero, ref data);
				}
			} // releases the Mutex
		}

        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Trace.WriteLine("PANIC! WE ARE SINKING! A ThreadException reached the highest of levels!");
            Trace.WriteLine("ERROR: " + e.Exception.Message);
            Trace.WriteLine(e.Exception.StackTrace);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Trace.WriteLine("PANIC! WE ARE SINKING! An Exception reached the highest of levels!");
            Trace.WriteLine("ERROR: " + ((Exception)e.ExceptionObject).Message);
            Trace.WriteLine(((Exception)e.ExceptionObject).StackTrace);
        }
		#endregion
		
		#region Event Handlers

        private void menuArchiveBrowser(object sender, EventArgs e)
        {
            FormArchiveBrowser f = new FormArchiveBrowser();
                f.Show();
        }

        private void menuChallenger(object sender, EventArgs e)
        {
            FormChallenger f = new FormChallenger();
            f.Show();
        }

        private void menuMatchMonitor(object sender, EventArgs e)
        {
            FormMatchMonitor f = new FormMatchMonitor();
                f.Show();
        }
        
        private void menuUploadManualClick(object sender, EventArgs e)
        {
            FormUpload up = new FormUpload(m_MatchLink, Properties.Settings.Default.Cookie, GatheredFiles, eventcollection, reminder.GameName, reminder.Mod);
                up.Show();
        }

        private void AequitasCheckerClick(object sender, EventArgs e)
        {
            AequitasChecker aeq = new AequitasChecker();
                aeq.Show();
        }

        private void menuAequitasBenchmarkClick(object sender, EventArgs e)
        {
            AequitasBenchmark aeq = new AequitasBenchmark();
                aeq.Show();
        }

        private void menuELOClick(object sender, EventArgs e)
        {
            FormELO elo = new FormELO();
                elo.Show();
        }

        /*private void menuELOClick(object sender, EventArgs e)
        {
            using (FormELO elo = new FormELO())
                elo.Show();
        }*/

        private void menuCreateSessionClick(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.Cookie != String.Empty)
                ESLHelpers.GetHTML("http://www.esl.eu/", new Cookie("COOKIE", Properties.Settings.Default.Cookie, "/", ".esl.eu"));
            else
                MessageBox.Show("You need to be logged in to use this function!");
            
        }

        private void menuTest2Click(object sender, EventArgs e)
        {
            StringCollection files = new StringCollection();
            files.AddRange(new string[] {
                /*@"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\esl2on2_kuh_nuke_ct_03.07.2007_01-22-19.dem",*/
                //@"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\de_nuke0040.bmp",
                //@"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\de_nuke0041.bmp",
                //@"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\dmeooo_17.09.2007_15-04-48.dem",
                //@"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\de_nuke0042.bmp",
                //@"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\dmeooo2.dem",
                //@"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\dmeooo3.dem",
                //@"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\de_aztec0021.bmp",
                //@"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\dmeooo4.dem",
                //@"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\de_aztec0022.bmp",
                @"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\demo_22.09.2007_02-41-44.dem",
                @"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\demo_22.09.2007_02-53-28.dem",
                @"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\demo_22.09.2007_03-08-56.dem",
                @"C:\Programme\Steam\steamapps\luigi2000@gmx.de\counter-strike\cstrike\demo_22.09.2007_03-23-02.dem",
                @"C:\Downloads\aequitas_0_9c\archive\7090752.ZIP"
            });
            FormUpload up = new FormUpload("http://www.esl.eu/de/cs/2on2/ladder/match/6769486/", Properties.Settings.Default.Cookie, files, eventcollection, reminder.GameName, reminder.Mod);
            up.Show();
        }
        private void menuReportClick(object sender, EventArgs e)
        {
            Process.Start(@"http://code.google.com/p/quicktools/issues/list");
        }
		private void menuAboutClick(object sender, EventArgs e)
		{
			MessageBox.Show(String.Format(lang.AboutProgram, Application.ProductVersion));
		}
		private void menuSettingsClick(object sender, EventArgs e)
		{
            FormSettings f = new FormSettings(ref reminder.WarnModules);
            f.FormClosed += new FormClosedEventHandler(f_FormClosed);
            f.Show();
            f.BringToFront();
            f.Focus();
		}

        void f_FormClosed(object sender, FormClosedEventArgs e)
        {
            SetUpReminder();
        }
		/*private void menuStopMonitoringClick(object sender, EventArgs e)
		{
			DontWarn = !DontWarn;
			((MenuItem)sender).Checked = DontWarn;
            //DemoBlinker.StopBlink();
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SysTrayIcon));
			if (DontWarn)
			{
				WatcherThread.Suspend();
				trayIcon.Icon = (Icon)resources.GetObject("disabled_small");
			}
			else
			{
				WatcherThread.Resume();
                firststart = true;
				trayIcon.Icon = (Icon)resources.GetObject("enabled_small");
			}
            notifier.StopNotify();
		}*/
		private void menuExitClick(object sender, EventArgs e)
		{
            //reminder.
            /*reminder.WantsToExit = true;
            while (reminder.dbg != null)
                Thread.Sleep(100);*/
            //reminder.osd.Stop();
			Application.Exit();
		}
		
		private void TrayIconDoubleClick(object sender, EventArgs e)
		{
            menuUploadManualClick(sender, e);
		}
		#endregion
	}
}
